const WebSocket=require("ws")
const server=new WebSocket.Server({port:8000});
server.on("connection",handleConnection);
function handleConnection(ws){
    console.log("------server is connected------");
    ws.on("close",handleClose);
    ws.on("error",handleError);
    ws.on("message",handleMessage);
}

function handleClose(e){
    console.log("------server is close------");
    this.send(JSON.stringify({
        mode:"MESSAGE",
        msg:'-----Server is closed-----'
    }));
}
function handleError(e){console.log("------server occured error------",e);}

/**
 * {
 *     mode:'MESSAGE' or 'HEART_BEAT'
 *     msg:string
 * }
 */
function handleMessage(data){
    const {mode,msg}=JSON.parse(data);
    switch (mode){
        case 'MESSAGE':
            console.log('-------User message-------')
            this.send(JSON.stringify(JSON.parse(data)));
            break;
        case 'HEART_BEAT':
            console.log('------heart beat message--------');
            this.send(JSON.stringify(JSON.parse(data)));
            break;
        default:
            break;
    }
}